<template>

  <el-form ref="formData" :model="formData" :rules="rules" label-width="80px">
    <el-form-item label="活动名称" prop="subjectName">
      <el-input v-model="formData.subjectName" />
    </el-form-item>
    <el-form-item label="是否显示" props="isFrontDisplay">
      <el-switch v-model="formData.isFrontDisplay" />
    </el-form-item>
    <el-form-item class="btn">
      <el-button type="primary" @click="addFn">确认</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>

</template>

<script>
import { add, detail, update } from '@/api/hmmm/subjects'
export default {

  name: '',
  props: {
    isEdit: {
      type: Boolean,
      required: true
    },
    id: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      formData: {
        subjectName: '',
        isFrontDisplay: 0
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getSubjectDetailById()
  },
  methods: {
    // 编辑学科调用的接口
    async Editor() {
      const res = await update(this.formData)
      this.$emit('renderList')
      if (res.status === 200) {
        this.$message.success('编辑成功!')
      }
      this.$emit('renderList')
    },

    // 添加学科调用的接口
    async addSubmit() {
      const res = await add(this.formData)
      console.log(res)
      // 3.刷新列表,给用户提示,关闭弹框
      this.$emit('renderList')
      if (res.status === 200) {
        this.$message.success('添加成功!')
      }
      this.$emit('renderList')
    },
    // 数据回显
    async getSubjectDetailById() {
      console.log(this.id)
      if (this.isEdit) {
        const res = await detail({ id: this.id })
        console.log(res.data, '....')
        this.formData = res.data
      }
    },
    // 取消新增学科
    cancel() {
      this.$emit('close')
    },
    // 新增学科
    addFn() {
      // 1.兜底验证
      this.$refs.formData.validate(async valid => {
        if (!valid) return
        // 2.调用 API
        this.isEdit ? this.Editor() : this.addSubmit()
        this.showDialog = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
.btn{
  margin-left:200px
}
</style>
